package com.tsj.spzx.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.tsj.spzx.Listener.ExcelListener;
import com.tsj.spzx.exception.TsjException;
import com.tsj.spzx.mapper.CategoryMapper;
import com.tsj.spzx.model.entity.product.Category;
import com.tsj.spzx.model.vo.common.ResultCodeEnum;
import com.tsj.spzx.model.vo.product.CategoryExcelVo;
import com.tsj.spzx.service.CategoryService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findByParentId(Long parentId) {
        // 1、根据分类id查询下级节点
        List<Category> categoryList = categoryMapper.findByParentId(parentId);
        // 2、判断下级节点的数量，如果为0， 则设置hasChildren 为false，那么就不会在前端展示出下拉框
        if (!CollectionUtil.isEmpty(categoryList)){
            //如果不为空，遍历他的下级节点,拿到所有下级节点的id
            List<Long> categoryIdList = new ArrayList<>();
            for (Category category : categoryList) {
                categoryIdList.add(category.getId());
            }
            // 查询他的所有下级节点的子节点的数量
            List<Long> childrenCountList = categoryMapper.findCountByParentId(categoryIdList);
            for (int i = 0; i < categoryList.size(); i++) {
                // 如果子节点的数量为0，则设置hasChildren为false
                if (childrenCountList.get(i) > 0){
                    categoryList.get(i).setHasChildren(true);
                }
            }
        }
        return categoryList;
    }

    @Override
    public void exportData(HttpServletResponse httpServletResponse) {
        try{
            // 1、设置响应头信息
            // 设置响应结果类型
            httpServletResponse.setContentType("application/vnd.ms-excel");
            httpServletResponse.setCharacterEncoding("utf-8");
            // URLEncoder.encode防止中文乱码
            String fileName = URLEncoder.encode("分类数据", StandardCharsets.UTF_8);
            httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 查出所有分类数据
            List<Category> categoryList = categoryMapper.findAll();
            // 接着将分类数据转换为 要导出的excel 对应的 实体类
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>();
            for (Category category : categoryList) {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                // BeanUtils.copyProperties 将一个类中的属性赋值给另一个类
                BeanUtils.copyProperties(category, categoryExcelVo);
                categoryExcelVoList.add(categoryExcelVo);
            }
            // 最后，将数据写入excel
            EasyExcel.write(httpServletResponse.getOutputStream(), CategoryExcelVo.class)
                    .sheet("分类数据").doWrite(categoryExcelVoList);

        }catch (Exception e){
            e.printStackTrace();
            throw new TsjException(ResultCodeEnum.DATA_ERROR);
        }

    }

    @Override
    public void importData(MultipartFile file) {
        try {
            ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<>(categoryMapper);
            EasyExcel.read(file.getInputStream(),CategoryExcelVo.class, excelListener)
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new TsjException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
